module x7seg(
    input [15:0] x,
    input clk,
    input clr_n,
    output reg [7:0] a_to_g,
    output reg [3:0] an
);

    reg [19:0] clkdiv;
    wire [1:0] s = clkdiv[19:18];
    reg [3:0] digit;

    always @(posedge clk or negedge clr_n) begin
        if (!clr_n)
            clkdiv <= 0;
        else
            clkdiv <= clkdiv + 1;
    end

    always @(*) begin
        case(s)
            2'd0: digit = x[3:0];
            2'd1: digit = x[7:4];
            2'd2: digit = x[11:8];
            2'd3: digit = x[15:12];
            default: digit = 4'd0;
        endcase
    end

    always @(*) begin
        case(digit)
            4'h0: a_to_g[6:0] = 7'b1111110;
            4'h1: a_to_g[6:0] = 7'b0110000;
            4'h2: a_to_g[6:0] = 7'b1101101;
            4'h3: a_to_g[6:0] = 7'b1111001;
            4'h4: a_to_g[6:0] = 7'b0110011;
            4'h5: a_to_g[6:0] = 7'b1011011;
            4'h6: a_to_g[6:0] = 7'b1011111;
            4'h7: a_to_g[6:0] = 7'b1110000;
            4'h8: a_to_g[6:0] = 7'b1111111;
            4'h9: a_to_g[6:0] = 7'b1111011;
            4'ha: a_to_g[6:0] = 7'b1110111;
            4'hb: a_to_g[6:0] = 7'b0011111;
            4'hc: a_to_g[6:0] = 7'b1001110;
            4'hd: a_to_g[6:0] = 7'b0111101;
            4'he: a_to_g[6:0] = 7'b1001111;
            4'hf: a_to_g[6:0] = 7'b1000111;
            default: a_to_g[6:0] = 7'b1111110;
        endcase

        //a_to_g[7] = (s == 2) ? 1 : 0;  // 第3个数码管小数点高电平点亮
    end

    always @(*) begin
        an = 4'b1111;  // 片选高电平关闭所有数码管
        if (clr_n)
            an[s] = 0; // 低电平选中当前数码管
    end
endmodule
